"""
系统管理相关的API路由
包括系统状态、日志管理、进程管理等
"""

from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import Dict, Any, List
import psutil
import os
from datetime import datetime

from database import get_db
from response_utils import success_response, error_response
from utils import LogManager
from process_manager import process_manager
from edge.edge_manager import edge_manager
from config import config
from services import TrainingService, ModelService, DatasetService, NodeService

router = APIRouter(prefix="/api/v1/system", tags=["system"])
logger = LogManager.get_logger(__name__)

@router.get("/status")
async def get_system_status():
    """获取系统状态信息"""
    try:
        # CPU使用率
        cpu_percent = psutil.cpu_percent(interval=1)
        
        # 内存使用情况
        memory = psutil.virtual_memory()
        
        # 磁盘使用情况
        disk = psutil.disk_usage('/')
        
        # 获取注册的进程信息
        registered_processes = process_manager.get_registered_processes_info()
        
        # 获取异步任务信息
        async_tasks = process_manager.get_async_tasks_info()
        
        status = {
            "service_status": "running",
            "timestamp": datetime.now().isoformat(),
            "version": config.api.version if hasattr(config, 'api') else "1.0.0",
            "system_resources": {
                "cpu_percent": cpu_percent,
                "memory_percent": memory.percent,
                "disk_percent": (disk.used / disk.total) * 100,
                "memory_used_gb": memory.used / (1024**3),
                "memory_total_gb": memory.total / (1024**3),
                "disk_used_gb": disk.used / (1024**3),
                "disk_total_gb": disk.total / (1024**3)
            },
            "process_info": {
                "registered_processes": len(registered_processes),
                "active_processes": sum(1 for info in registered_processes.values() if info.is_alive()),
                "async_tasks": len(async_tasks),
                "active_async_tasks": sum(1 for info in async_tasks.values() if not info.is_done())
            }
        }
        
        return success_response(
            data=status,
            message="获取系统状态成功"
        )
    except Exception as e:
        logger.error(f"获取系统状态失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"获取系统状态失败: {str(e)}")

@router.get("/processes")
async def get_process_info():
    """获取进程管理信息"""
    try:
        # 获取注册的进程信息
        registered_processes = process_manager.get_registered_processes_info()
        
        # 获取异步任务信息
        async_tasks = process_manager.get_async_tasks_info()
        
        # 获取边侧连接任务
        edge_tasks = process_manager.get_edge_connection_tasks()
        
        process_info = {
            "registered_processes": {
                pid: {
                    "pid": info.pid,
                    "name": info.name,
                    "process_type": info.process_type,
                    "start_time": info.start_time,
                    "task_id": info.task_id,
                    "status": info.status,
                    "is_alive": info.is_alive()
                } for pid, info in registered_processes.items()
            },
            "async_tasks": {
                task_id: {
                    "task_id": info.task_id,
                    "name": info.name,
                    "task_type": info.task_type,
                    "start_time": info.start_time,
                    "status": info.status,
                    "related_nodes": info.related_nodes,
                    "is_done": info.is_done()
                } for task_id, info in async_tasks.items()
            },
            "edge_connection_tasks": [
                {
                    "task_id": info.task_id,
                    "name": info.name,
                    "task_type": info.task_type,
                    "start_time": info.start_time,
                    "status": info.status,
                    "related_nodes": info.related_nodes,
                    "is_done": info.is_done()
                } for info in edge_tasks
            ],
            "summary": {
                "total_processes": len(registered_processes),
                "active_processes": sum(1 for info in registered_processes.values() if info.is_alive()),
                "total_async_tasks": len(async_tasks),
                "active_async_tasks": sum(1 for info in async_tasks.values() if not info.is_done()),
                "edge_tasks_count": len(edge_tasks),
                "active_edge_tasks": sum(1 for info in edge_tasks if not info.is_done())
            }
        }
        
        return success_response(
            data=process_info,
            message="获取进程信息成功"
        )
    except Exception as e:
        logger.error(f"获取进程信息失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"获取进程信息失败: {str(e)}")

@router.post("/processes/cleanup-async-tasks")
async def cleanup_async_tasks():
    """清理所有异步任务"""
    try:
        # 取消所有异步任务
        results = process_manager.cancel_all_async_tasks()
        
        # 清理EdgeManager中的任务
        edge_manager.cleanup_all_tasks()
        
        return success_response(
            data={
                "cancelled_tasks": results,
                "total_cancelled": len(results),
                "successful_cancellations": sum(results.values())
            },
            message="异步任务清理完成"
        )
    except Exception as e:
        logger.error(f"清理异步任务失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"清理异步任务失败: {str(e)}")

@router.post("/processes/cleanup-edge-tasks")
async def cleanup_edge_tasks():
    """专门清理边侧连接相关的异步任务"""
    try:
        # 按类型取消边侧任务
        edge_types = ['edge_connection', 'batch_operation', 'sample_collection', 'health_check']
        results = {}
        
        for task_type in edge_types:
            type_results = process_manager.cancel_async_tasks_by_type(task_type)
            results[task_type] = type_results
        
        # 清理EdgeManager中的任务
        edge_manager.cleanup_all_tasks()
        
        total_cancelled = sum(len(type_results) for type_results in results.values())
        successful_cancelled = sum(
            sum(type_results.values()) for type_results in results.values()
        )
        
        return success_response(
            data={
                "cancelled_by_type": results,
                "total_cancelled": total_cancelled,
                "successful_cancellations": successful_cancelled
            },
            message="边侧任务清理完成"
        )
    except Exception as e:
        logger.error(f"清理边侧任务失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"清理边侧任务失败: {str(e)}")

@router.get("/resources")
async def get_resource_usage():
    """获取系统资源使用情况"""
    try:
        # CPU使用率
        cpu_percent = psutil.cpu_percent(interval=1)
        
        # 内存使用情况
        memory = psutil.virtual_memory()
        
        # 磁盘使用情况
        disk = psutil.disk_usage('/')
        
        # 网络IO
        network = psutil.net_io_counters()
        
        resources = {
            "cpu": {
                "percent": cpu_percent,
                "count": psutil.cpu_count(),
                "count_logical": psutil.cpu_count(logical=True)
            },
            "memory": {
                "total": memory.total,
                "available": memory.available,
                "percent": memory.percent,
                "used": memory.used,
                "free": memory.free
            },
            "disk": {
                "total": disk.total,
                "used": disk.used,
                "free": disk.free,
                "percent": (disk.used / disk.total) * 100
            },
            "network": {
                "bytes_sent": network.bytes_sent,
                "bytes_recv": network.bytes_recv,
                "packets_sent": network.packets_sent,
                "packets_recv": network.packets_recv
            },
            "process_info": {
                "current_pid": os.getpid(),
                "parent_pid": os.getppid() if hasattr(os, 'getppid') else None
            }
        }
        
        return success_response(
            data=resources,
            message="获取系统资源使用情况成功"
        )
    except Exception as e:
        logger.error(f"获取系统资源使用情况失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"获取系统资源使用情况失败: {str(e)}")

@router.get("/overview")
async def get_system_overview(db: Session = Depends(get_db)):
    """获取云端系统概览统计信息，包括模型、训练任务、数据集、节点的总数量"""
    try:
        # 初始化服务实例
        training_service = TrainingService()
        model_service = ModelService()
        dataset_service = DatasetService()
        node_service = NodeService()
        
        # 获取各种资源的总数量统计
        from database import TrainingTask, Model, Dataset, Node
        
        # 获取总数量
        total_training_tasks = db.query(TrainingTask).count()
        total_models = db.query(Model).count()
        total_datasets = db.query(Dataset).count()
        total_nodes = db.query(Node).count()
        
        # 获取详细统计信息
        training_summary = training_service.get_training_tasks_summary(db)
        model_summary = model_service.get_models_summary(db)
        dataset_summary = dataset_service.get_datasets_summary(db)
        node_summary = node_service.get_nodes_summary(db)
        
        # 组织响应数据
        overview_data = {
            "totals": {
                "training_tasks": total_training_tasks,
                "models": total_models,
                "datasets": total_datasets,
                "nodes": total_nodes
            },
            "details": {
                "training_tasks": training_summary,
                "models": model_summary,
                "datasets": dataset_summary,
                "nodes": node_summary
            },
            "timestamp": datetime.now().isoformat()
        }
        
        return success_response(
            data=overview_data,
            message="获取云端系统概览统计信息成功"
        )
        
    except Exception as e:
        logger.error(f"获取云端系统概览统计信息失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"获取云端系统概览统计信息失败: {str(e)}") 